package com.kevin.blog.dao;

import com.kevin.blog.po.Blog;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Author Kevin
 * @Date 2021-04-24 17:41:21
 */
public interface BlogRepository extends JpaRepository<Blog, Long>, JpaSpecificationExecutor<Blog> {

    /**
     * 推荐前几个博客的页面查询方法
     */
    @Query("select b from Blog b where b.recommend=true")
    List<Blog> findTop(Pageable pageable);

    /**
     * 全局搜索实现
     */
    @Query("select b from Blog b where b.title like ?1 or b.content like ?1")
    Page<Blog> findByQuery(String query, Pageable pageable);

    /**
     * 自定义SQL之浏览次数
     *
     * @param id
     * @return
     */
    @Transactional
    @Modifying
    @Query("update Blog b set b.views=b.views+1 where b.id=?1")
    int updateViews(Long id);

    /**
     * 逆序排序年份
     * SELECT date_format(b.update_time,'%Y') as year from t_blog b GROUP BY  year ORDER BY year DESC;
     *
     * @return
     */
    @Query("select function('date_format',b.updateTime,'%Y') as year from Blog b group by function('date_format',b.updateTime,'%Y') order by function('date_format',b.updateTime,'%Y') desc")
    List<String> findGroupYear();

    /**
     * 进行年份的查询
     * SELECT * from t_blog b where date_format(b.update_time,'%Y')='2018';
     *
     * @return
     */
    @Query("select b from Blog b where function('date_format',b.updateTime,'%Y') = ?1")
    List<Blog> findByYear(String year);

}
